<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Response;

class ResponseMacroServiceProvider extends ServiceProvider
{
    /**
     * Register the application's response macros.
     *
     * @return void
     */
    public function boot()
    {
        Response::macro('success', function ($data=[]) {


            $res=[];
            $res['code'] = 0;
            $res['msg'] = isset($data['msg']) ? $data['msg'] : '';
            //if(!$data) $data = (object)$data;
            $res['data'] = $data;
            return Response::json($res);

        });

        Response::macro('error', function ($name, $data=[]) {
            $error = config('error');
            $res=[];
            $res['code'] = (int)$error[$name]['code'];
            $res['msg'] = $error[$name]['msg'];
            if($data) $res['data'] = $data;
            return Response::json($res);
        });

        Response::macro('item', function ($trans, $data) {
            if($data)
            {
                return response()->success($trans->transform($data));
            }else{
                return response()->error('NOT_EXIST');
            }
        });

        Response::macro('collection', function ($trans, $data) {
            $ret_data = [];
            if($data)
            {
                foreach ($data as $item)
                {
                    $ret_data[] = $trans->transform($item);
                }
            }
            return response()->success($ret_data);
        });

        Response::macro('pagination', function ($paginator) {
            $ret = [];
            $ret['list'] = $paginator->items();
            if($paginator)
            {
                $ret['meta']= [
                    'total'=>(int)$paginator->total(),
                    'per_page'=>(int)$paginator->perPage(),
                    'current_page'=>(int)$paginator->currentPage(),
                    'last_page'=>(int)$paginator->lastPage(),
                    'next_page_url'=>(string)$paginator->nextPageUrl(),
                    'prev_page_url'=>(string)$paginator->previousPageUrl()
                ];
            }
            return response()->success($ret);
        });
        
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

}